import json, requests, os, time
from urllib.parse import quote
from pathlib import Path
from PIL import Image
import io

# ---------- 会话头保持不变 ----------
session = requests.Session()
session.headers.update({
    "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                   "AppleWebKit/537.36 (KHTML, like Gecko) "
                   "Chrome/114.0 Safari/537.36"),
    "Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8",
    "Referer": "https://h5.ele.me/",
})
try:
    session.get("https://h5.ele.me/", timeout=10)
except Exception:
    pass
# ------------------------------------

def square_1200(img_bytes: bytes) -> bytes:
    """把任意图片转成 1200×1200 JPEG 字节流"""
    im = Image.open(io.BytesIO(img_bytes)).convert("RGB")
    w, h = im.size
    # 1. 先缩放到短边 1200
    if w < h:
        new_w = 1200
        new_h = int(1200 * h / w)
    else:
        new_h = 1200
        new_w = int(1200 * w / h)
    im = im.resize((new_w, new_h), Image.LANCZOS)

    # 2. 中心裁剪 1200×1200
    left = (new_w - 1200) // 2
    top  = (new_h - 1200) // 2
    im = im.crop((left, top, left + 1200, top + 1200))

    # 3. 保存到内存字节流
    out = io.BytesIO()
    im.save(out, format="JPEG", quality=95)
    return out.getvalue()

def main():
    os.makedirs("pic", exist_ok=True)
    with open("response.json", "r", encoding="utf-8") as f:
        data = json.load(f)

    for food in data["data"]["data"]:
        name  = food["title"]
        img_url = quote(food["picUrl"], safe="/:")
        safe_name = name.replace("【", "").replace("】", "").replace("/", "_").replace("\\", "_")

        for attempt in range(3):
            try:
                resp = session.get(img_url, timeout=15, stream=True)
                if resp.status_code == 420:
                    time.sleep(3 << attempt)
                    continue
                resp.raise_for_status()
                raw_bytes = resp.content

                # 关键：统一转成 1200×1200
                jpeg_1200 = square_1200(raw_bytes)

                file_path = os.path.join("pic", f"{safe_name}.jpeg")
                with open(file_path, "wb") as f:
                    f.write(jpeg_1200)
                print(f"1200×1200 图片已保存：{file_path}")
                break
            except Exception as e:
                print(f"下载/处理失败：{e}，第{attempt+1}次")
        else:
            print(f"跳过图片：{name}")

if __name__ == '__main__':
    main()